package cn.yunyichina.provider.bone.service.impl;

import cn.yunyichina.provider.bone.vo.BoneVo;
import cn.yunyichina.provider.framework.common.PKGenerator;
import cn.yunyichina.provider.framework.dubbo.service.BaseService;
import cn.yunyichina.provider.framework.dubbo.service.CacheService;
import cn.yunyichina.provider.framework.dubbo.service.MessageService;
import cn.yunyichina.provider.framework.dubbo.service.PayService;
import cn.yunyichina.provider.iface.entity.base.OrderExtVo;
import cn.yunyichina.provider.iface.entity.common.Response;
import cn.yunyichina.provider.iface.entity.common.ResponseObject;
import cn.yunyichina.utils.commons.DateUtils;
import cn.yunyichina.utils.convert.JsonUtils;
import cn.yunyichina.utils.convert.ObjectParser;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 骨科大会
 * Created by Administrator on 2017/2/10.
 */
@Service
public class BoneMeetingServiceImpl {
    private static final Logger logger = LoggerFactory.getLogger(BoneMeetingServiceImpl.class);

    private static final String platformId="1d946fbaa26b11e6951000163e00175d";
    private static final String platformName="广州云医科技有限公司";
    private static final String platformCode="yykj";
    private static final String platformOrgAppCode="boneeouwe647dhat231";
    private static final String platformOrgAppName="骨科大会报名系统";


    private static final String orgCode="yykj";
    private static final String orgId="1d946fbaa26b11e6951000163e00175d";
    private static final String orgName="广州云医科技有限公司";
    private static final Integer payAmount=1;


    /**骨科大会报名
     * yyt.bone.bone.meeting.sign
     * @param data
     * @return
     */
    public ResponseObject SignBoneMeeting(String data) {
        logger.info("SignBoneMeeting data: "+data);
        ResponseObject response = new ResponseObject();
        BoneVo vo = JsonUtils.parseObject(data, BoneVo.class);

        OrderExtVo order = new OrderExtVo();
//        order.setOpenId(requestVo.getOpenId());

        order.setId(PKGenerator.generateId());
        order.setPlatformId(platformId);
        order.setPlatformName(platformName);
        order.setPlatformCode(platformCode);
        order.setPlatformOrgAppCode(platformOrgAppCode);
        order.setPlatformOrgAppName(platformOrgAppName);

        order.setOrderNo(CacheService.generateOrderNum(2, 1));
        order.setOpenId(vo.getOpenId());
        order.setOrgCode(orgCode);
//        order.setBranchCode(branchCode);
        order.setOrgId(orgId);
        order.setOrgName(orgName);
        order.setOrderStatusCreate();
        order.setPayStatusNotPay();
        order.setOrderType(OrderExtVo.ORDER_TYPE_BONE);
        order.setPayMode((short) 0);
        order.setUserName(vo.getName());
        order.setUserAddress(vo.getArea());
        order.setPayUserId("");
        order.setIdCardNo(vo.getIdCardNo());
        order.setIdCardType((short) 1);
        order.setUserMobile(vo.getPhone());
        order.setUserSex(vo.getSex());
//        order.setDoctorCode(mzfee.getDoctorCode());
//        order.setDoctorName(mzfee.getDoctorName());
//        order.setDeptCode(mzfee.getDeptCode());
//        order.setDeptName(mzfee.getDeptName());
        order.setCreatedTime( DateUtils.dateToString(new Date()));
        order.setIsInsurance((short) 0);
        order.setPayAmount(payAmount);
        order.setPayRealAmount(payAmount);
        order.setTotalAmount(payAmount);
        order.setAccountAmount(0);
        order.setMedicareAmount(0);
        order.setInsuranceAmount(0);

        Map<String, String> extraParamsMap = new HashMap<String, String>();
        extraParamsMap.put("hospital",vo.getHospitalName());
        extraParamsMap.put("dept",vo.getDeptName());
        extraParamsMap.put("auth_img",vo.getAuthImg());
        extraParamsMap.put("interest",vo.getInterest());
        extraParamsMap.put("title",vo.getTitle());
        order.setExtraParams(JsonUtils.toJsonString(extraParamsMap));

        Response baseRespone =  BaseService.callUnderlineFromInternal("",
                "yyt.base.order.add", JsonUtils.toJsonString(order));
        logger.info("生成骨科大会报名订单：base返回" + JsonUtils.toJsonString(baseRespone));
        if(!baseRespone.getResultCode().equals("0")){
            response.setResultCodeAndMessage("1001","生成骨科大会报名订单失败");
            return response;
        }
        response.setResultCodeAndMessage("0","生成订单成功");
        response.setResultObject(order);
        return response;
    }


    /**
     * 报名审核 yyt.bone.bone.meeting.approve
     * @param data
     * @return
     */
    public ResponseObject ApproveBoneMeeting(String data) {
        logger.info("ApproveBoneMeeting data: "+data);
        Map map = JsonUtils.parseObject(data, Map.class);
        ResponseObject response = new ResponseObject();

        String orderNo = (String) map.get("order_no");
        String pass = (String) map.get("pass");
        if(StringUtils.isBlank(orderNo) || pass == null){
            response.setResultCodeAndMessage("1001","审核入参错误");
            return response;
        }
        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put("order_no", orderNo);
        Response ordResponse = BaseService.callUnderlineFromInternal("", "yyt.base.order.by.order.no.out.get",
                JsonUtils.toJsonString(dataMap));
        if(!"0".equals(ordResponse.getResultCode())) {
            response.setResultCodeAndMessage("1001","查询订单出错");
            return response;
        }
        OrderExtVo orderExtVo = JsonUtils.parseObject(ordResponse.getResult(), OrderExtVo.class);
        if("1".equals(pass) && orderExtVo.getOrderStatus() != OrderExtVo.ORDER_STATUS_SUCCESS){
            //审核通过
            orderExtVo.setOrderStatusSuccess();
            orderExtVo.setUpdateTime(DateUtils.dateToString(new Date()));
             BaseService.callUnderlineFromInternal("",
                    "yyt.base.order.update", JsonUtils.toJsonString(orderExtVo));
            //发送短信
            String msgStr = "{\"user_type\":\"5\",\"to_user\":\"" + orderExtVo.getUserMobile() +
                    "\",\"msg_type\":4,\"msg_content\":{\"name\":\"" + orderExtVo.getUserName() +"\"}}";
            MessageService.callUnderlineFromInternal("",
                    "yyt.message.msg.sms.send", msgStr);
        }else if("0".equals(pass) && orderExtVo.getOrderStatus() != OrderExtVo.ORDER_STATUS_CANCEL
            && orderExtVo.getPayStatus() == OrderExtVo.ORDER_PAY_STATUS_PAYED) {
                //审核不通过，退费
                Map<String, Object> jsonMap = new HashMap<String, Object>();
                jsonMap.put("hospital_code", orderExtVo.getOrgCode());
                jsonMap.put("order_no", orderExtVo.getOrderNo());
                jsonMap.put("his_order_no", orderExtVo.getHisOrderNo());
//            jsonMap.put("his_serial_no", orderExtVo;
                jsonMap.put("refund_amount", orderExtVo.getPayAmount());
                jsonMap.put("refund_time", DateUtils.dateToString(new Date()));
                jsonMap.put("refund_reason", "审核不通过");
                jsonMap.put("refund_flag", 1);
                jsonMap.put("push_type", 0);
                Response refundResponse = PayService.callUnderlineFromInternal("", "yyt.pay.refund.channel.origin", JsonUtils.toJsonString(jsonMap));
                logger.info("ApproveBoneMeeting：退费返回" + JsonUtils.toJsonString(refundResponse));
                if ("0".equals(refundResponse.getResultCode())) {
                    orderExtVo.setOrderStatusCancel();
                    orderExtVo.setPayStatusRefunded();
                    orderExtVo.setUpdateTime(DateUtils.dateToString(new Date()));
                    BaseService.callUnderlineFromInternal("",
                            "yyt.base.order.update", JsonUtils.toJsonString(orderExtVo));

                    //发送短信
                    String msgStr = "{\"user_type\":\"5\",\"to_user\":\"" + orderExtVo.getUserMobile() +
                            "\",\"msg_type\":5,\"msg_content\":{\"name\":\"" + orderExtVo.getUserName() +"\"}}";
                    MessageService.callUnderlineFromInternal("",
                            "yyt.message.msg.sms.send", msgStr);
                } else {
                    response.setResultCodeAndMessage(refundResponse.getResultCode(), refundResponse.getResultMessage());
                    return response;
                }

        }else{
            response.setResultCodeAndMessage("-1", "订单已审核");
            return response;
        }

        response.setResultCodeAndMessage("0","审核成功");
        return response;
    }
}
